from django.db.models import Q
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
# from django.contrib.auth.models import AnonymousUser
from django.shortcuts import render, get_object_or_404, reverse, Http404, HttpResponse
from django.views.generic import (CreateView, DeleteView, DetailView, ListView,
                                  UpdateView)

from guardian.mixins import PermissionListMixin, PermissionRequiredMixin, LoginRequiredMixin
from guardian.shortcuts import assign_perm

from .models import BlogPost
from .forms import BlogPostForm


class OwnDraftQueryMixin(object):
    def get_queryset(self):
        user = self.request.user
        if user.is_authenticated:
            return self.model.objects.filter(author=self.request.user,
                                             is_published=False)
        #     return BlogPost.objects.filter(
        #         Q(is_published=True) | Q(author=self.request.user))
        # else:
        #     return BlogPost.objects.filter(is_published=True)


# @method_decorator(login_required, name='dispatch')
class BlogPostCreateView(LoginRequiredMixin, PermissionRequiredMixin,
                         CreateView):
    model = BlogPost
    template_name = "blog/add.html"
    form_class = BlogPostForm
    permission_object = None
    permission_required = 'blog.add_blogpost'

    def form_valid(self, form, *args, **kwargs):
        self.object = form.save(commit=False)
        self.object.author = self.request.user
        self.object.save()
        # resp = super().form_valid(form, *args, **kwargs)
        assign_perm('view_blogpost', self.request.user, self.object)
        assign_perm('change_blogpost', self.request.user, self.object)
        assign_perm('delete_blogpost', self.request.user, self.object)
        return HttpResponseRedirect(self.get_success_url())
        # return resp

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super().get_form_kwargs(*args, **kwargs)
        kwargs['author'] = self.request.user
        return kwargs


class BlogPostListView(OwnDraftQueryMixin, PermissionListMixin, ListView):
    model = BlogPost
    template_name = "blog/list.html"
    paginate_by = 5
    permission_required = 'blog.view_blogpost'

    def get_queryset(self):
        queryset = super().get_queryset()
        if not queryset:
            queryset = BlogPost.objects.filter(is_published=True)
        else:
            queryset = (queryset | BlogPost.objects.filter(is_published=True))

        return queryset


class BlogPostDetailView(OwnDraftQueryMixin, PermissionRequiredMixin,
                         DetailView):
    model = BlogPost
    template_name = "blog/detail.html"
    permission_required = []

    def get_queryset(self):
        queryset = super().get_queryset()

        if not queryset:
            queryset = BlogPost.objects.filter(is_published=True)
        else:
            queryset = (queryset | BlogPost.objects.filter(is_published=True))
        return queryset

    # def get_object(self, queryset=None):
    #     obj = super().get_object(queryset=queryset)
    #     if obj.author != self.request.user:
    #     slug = self.kwargs.get("slug")
    #     queryset = queryset or self.get_queryset()
    #     print(queryset, "===============")
    #     if not queryset:
    #         raise Http404

    #     try:
    #         # print(queryset)
    #         object = queryset.get(slug=slug)
    #     except:
    #         raise Http404
    #     return object


# @method_decorator(login_required, name='dispatch')
class BlogPostDeleteView(LoginRequiredMixin, PermissionRequiredMixin,
                         DeleteView):
    model = BlogPost
    template_name = "blog/delete.html"
    success_url = reverse_lazy('blog:list')
    permission_required = ['view_blogpost', 'delete_blogpost']

    return_404 = True

    # def get(self, request, *args, **kwargs):
    #     obj = self.get_object()
    #     if obj.author != self.request.user:
    #         response = HttpResponse("You do not have permission to do this.")
    #         response.status_code = 403
    #         return response
    #     context = {'blogpost': obj}
    #     return render(request, self.template_name, context)

    def get_object(self, queryset=None):
        slug = self.kwargs.get("slug")
        try:
            obj = BlogPost.objects.get(slug=slug)
        except BlogPost.DoesNotExist:
            raise Http404

        return obj

    # def get_success_url(self):
    #     return reverse('blog:list')


# @method_decorator(login_required, name='dispatch')
class BlogPostUpdateView(LoginRequiredMixin, PermissionRequiredMixin,
                         UpdateView):
    model = BlogPost
    template_name = "blog/edit.html"
    form_class = BlogPostForm
    permission_required = ['view_blogpost', 'change_blogpost']
